package com.lis.scf.service.impl;



import com.lis.scf.entity.Role;
import com.lis.scf.entity.User;
import com.lis.scf.repository.UserRepository;
import com.lis.scf.service.UserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * Spring Security的用户详情服务实现
 * 用于加载用户信息（用户名、密码、权限等）
 */
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    /**
     * 根据用户名加载用户信息（Spring Security自动调用）
     */
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 从数据库查询用户
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户名不存在: " + username));

        // 2. 验证用户状态（是否激活）
        if (!user.getIsActive()) {
            throw new UsernameNotFoundException("用户已被禁用: " + username);
        }

        // 3. 转换用户角色为Spring Security需要的权限格式（ROLE_前缀）
        Collection<? extends GrantedAuthority> authorities = user.getRoles().stream()
                .map(Role::getRoleName)
                .map(roleName -> new SimpleGrantedAuthority("ROLE_" + roleName)) // 角色必须以ROLE_开头
                .collect(Collectors.toList());

        // 4. 返回Spring Security的UserDetails对象
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword()) // 数据库中已加密的密码
                .authorities(authorities) // 用户拥有的角色/权限
                .accountExpired(false) // 账号未过期
                .accountLocked(false) // 账号未锁定
                .credentialsExpired(false) // 凭证未过期
//                .enabled(user.getIsActive()) // 是否启用
                .build();
    }
}
